// 1. 启动json-server: json-server --port 3005 --watch ./json-server/db.json
$(function () {
  let $template = $("#template");
  let templateCodeMirror = CodeMirror($template[0], {
    value: "",
    mode: "javascript",
    lineNumbers: true,
    tabSize: 2,
  });

  let $mode = $("#mode");
  let modeCodeMirror = CodeMirror($mode[0], {
    value: "",
    mode: "javascript",
    lineNumbers: true,
    tabSize: 2,
  });

  let $result = $("#result");
  let resultCodeMirror = CodeMirror($result[0], {
    value: "",
    mode: "javascript",
    lineNumbers: true,
    tabSize: 2,
  });

  $("#readTpl").click(function () {
    let tpl = localStorage.getItem("tpl") || "";
    templateCodeMirror.doc.setValue(tpl);
    let model = localStorage.getItem("model") || "";
    modeCodeMirror.doc.setValue(model);
  });

  $("#saveTpl").click(function () {
    let tpl = templateCodeMirror.doc.getValue();
    localStorage.setItem("tpl", tpl);
    let model = modeCodeMirror.doc.getValue();
    localStorage.setItem("model", model);
  });

  $("#gen").click(function () {
    let tStr = templateCodeMirror.doc.getValue();
    let mStr = modeCodeMirror.doc.getValue() || {};
    let arr = mStr.split("\n");

    // let map = arr
    //   .map((item) => item.split("="))
    //   .reduce((pre, cur) => {
    //     pre[cur[0]] = cur[1];
    //     return pre;
    //   }, {});

    let map = JSON.parse(mStr);

    $.ajax({
      type: "POST",
      url: "/api/lcdp/test/genCode",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({ codeTemplate: tStr, map }),
      // dataType: "json",
      success: (data) => {
        if (data.code === "200") resultCodeMirror.doc.setValue(data.data);
        else resultCodeMirror.doc.setValue(data.msg);
      },
      error: (err) => {
        console.error(err);
      },
    });
  });
});
